#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2019/10/15 16:15
# @Author  : ZRD
# @File    : data_check.py
#  https://www.jianshu.com/p/36a0f90028f3


import traceback, sys

from schema import Regex, And, Use, Optional, Schema, Hook


class Deprecated(Hook):
    def __init__(self, *args, **kwargs):
        kwargs["handler"] = lambda key, *args: print(f"`{key}` is deprecated. " + (self._error or ""))
        super(Deprecated, self).__init__(*args, **kwargs)


def check_register_params(data):
    """ 校验创建新账号的参数
        name: string 由7—15个字母、数字、下划线组成
        phone: string 11位手机号
        education: int 1:primary school; 2: junior high school; 3: High school;
                        4: bachelor; 5: master; 6: doctor
        age: int [7-150] 可选
        level: high、middle、low
        grade: int 可选
    """
    level_list = ["high", "middle", "low"]
    mode_dict = {
        "task_name": Regex("[a-zA-Z0-9_]{1,255}", error="task_name应为1-255位字母、数字、下划线组成"),
        "phone": Regex("^(0|86|17951)?(13[0-9]|15[012356789]|18[0-9]|14[57]|17[678])[0-9]{8}$", error="手机号不正确"),
        "education": And(int, lambda x: 0 < x < 7, error="education应该为0-6之间的整数"),
        Optional("age", default="sing"): And(int, lambda x: 7 < x < 150, error="age应该为7-150之间的整数"),
        "level": And(str, lambda x: x in level_list, error="level的可选值为high、middle、low"),
        Optional("pre_ommand", default=""): Use(str, error="应为字符串"),
        Optional("post_ommand", default=""): Use(str, error="应为字符串"),
        Optional("workdir", default="."): Use(str, error="应为字符串"),
    }
    try:
        results = Schema(mode_dict).validate(data)
        # results = Schema(mode_dict,Deprecated(), ).validate(data)
    except Exception as ex:

        _, exc_value, _ = sys.exc_info()
        print(str(exc_value))

        # print("检验错误: %r" % ex)

    else:
        print("结果正常:", results)


if __name__ == '__main__':
    # 验证通过的参数
    data = {
        "name": "12345678",
        "phone": "18329269224",
        "education": 6,
        "age": 8888,
        "level": "middle",
        "grade": 86
    }
    # check_register_params(data)

    # name不合法
    # data = {
    #     "name": "123",
    #     "phone": "18329269224",
    #     "education": 6,
    #     "age": 8,
    #     "level": "middle",
    #     "grade":86
    # }
    # check_register_params(data)

    # 少了必填参数
    # data = {
    #     "name": "hji123345",
    #     "phone": "18329269224"
    # }
    check_register_params(data)
